package myapp.drawable_items;

import myapp.DTO.ServiceDTO;
import myapp.dictionary.MyDictionary;
import myapp.helper.OrientationHelper;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class PreviewDraw extends View {

	private static final String TAG = "PreviewDraw";
	private SmallItemList items;
	Paint p;
	private double maxDistance;
	
	public void setMaxDistance(double _maxDistance)
	{
		maxDistance = _maxDistance;
	}
	
	public int getItemListSize()
	{
		return items.size();
	}
	
	public PreviewDraw(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		p = new Paint();
		items = new SmallItemList();
		SetUpDemo();
	}
	
	private void SetUpDemo(){
/*		items.add(new smallItem(20, 20, "Icon 1", getResources(), R.drawable.home_icon1));
		items.add(new smallItem(10, 250, "Icon 2", getResources(), R.drawable.home_icon1));*/
	}
	
	public void clearItems()
	{
		items.clear();
		Log.d("PreviewDraw", "clearItem");
	}
	
	public void addStaticItem(ServiceDTO service, float x, float y, int bitmapID)
	{
		items.add(new smallItem(service, y, x, service.getName(), getResources(), bitmapID, false));
	}
	
	public void addMovableItem(ServiceDTO service, double lat, double lon, float offsetX, float offsetY, double yaw, double degreeView) {		
		double degree = 0;
		degree = OrientationHelper.getDegreeOrientationDeviceWithService(lon, lat, service, (float)yaw);
		double xScale = degree / (degreeView / 2);
		double distance = OrientationHelper.CalculateDistanceBetweenTwoPoints(lon, lat, service.getLongitude(), service.getLatitude()); 
		double yScale = distance / this.maxDistance;
		items.add(new smallItem(service , offsetY - offsetY*(float)yScale, offsetX + offsetX*(float)xScale, service.getName(), getResources(), MyDictionary.dictionary.get(service.getCategoryId()), true));
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		p.setStyle(Paint.Style.FILL);
		p.setColor(Color.RED);
		Log.d(TAG, "draw");

		items.DrawAllItems(canvas, p);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		float x = event.getX();
		float y = event.getY();
		
		smallItem item = items.getTouchedItem(x, y);
		if (item != null){
			AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
			dialog.setTitle(item.getServiceDTO().getName());
			dialog.setMessage(item.getServiceDTO().getAddress());
			dialog.setNegativeButton("OK", null);
			dialog.show();
		}
		
		Log.d(TAG, "On Touch event. X = " + x + "  Y = " + y);
		return super.onTouchEvent(event);
	}
}
